package com.xyy.saas.payment.adpater.abchinaLoan;

import cn.hutool.core.io.FileUtil;
import com.abchina.openbank.OpenBankHttpClient;
import com.abchina.openbank.OpenBankHttpRequest;
import com.abchina.openbank.common.Contants;
import com.alibaba.fastjson.JSON;
import com.xyy.saas.payment.adpater.abchinaLoan.core.req.ApplyH5Dto;
import com.xyy.saas.payment.adpater.abchinaLoan.core.req.OrderChangeDto;
import com.xyy.saas.payment.adpater.abchinaLoan.core.req.OrderCheckDto;
import com.xyy.saas.payment.adpater.abchinaLoan.core.req.QueryLoanDto;
import com.xyy.saas.payment.adpater.abchinaLoan.core.resp.OrderChangeNotifyResp;
import com.xyy.saas.payment.adpater.abchinaLoan.core.resp.OrderCheckResp;
import com.xyy.saas.payment.adpater.abchinaLoan.core.resp.QueryLoanStatusResp;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author wangzeqi
 */
public class AbchinaLoanSdkDemo {

    //第一个是合作方自己的证书；第二个是合作方自己的证书密码；第三个是农行的公钥证书；
    //文件路径请自行配置
    //两个证书都在配套文件夹中，illegel key size报错时见文档【开放银行服务端SDK使用手册-JAVA-V1.3.0.wps】
    private static final String pfxFile;
    private static final String pfxPwd = "111111";
    private static final String cerFile;

    private static final String pfxFileName;
    private static final String cerFileName;

    static {
        pfxFile = Objects.requireNonNull(AbchinaLoanSdkDemo.class.getClassLoader().getResource("abchina-dev.pfx")).getPath();
        cerFile = Objects.requireNonNull(AbchinaLoanSdkDemo.class.getClassLoader().getResource("abchina-dev.cer")).getPath();

        pfxFileName = "abchina-dev.pfx";
        cerFileName = "abchina-dev.cer";
    }

    // TODO 测试前请联系开放银行分配appId
    // 此appid不限ip
    private static final String appId = "b6e9e2c7-3aba-40c5-81ed-20913c1f0352";

    //AES对称加密的密钥
    private static final String appSecret = "cff054d1d7c84036a3dc160f9457e5f423704b15";
    //可选contentType："application/json"，"application/xml"
    //                "application/x-www-form-urlencoded"
    private static final String contentType = "application/json";

    public static void main(String[] args) throws Exception {

        InputStream pfxFileStream = new ClassPathResource(pfxFileName).getInputStream();
        InputStream cerFileStream = new ClassPathResource(cerFileName).getInputStream();
        OpenBankHttpClient.initOpenBankHttpClient(appId, pfxFileStream, pfxPwd, cerFileStream, appSecret);


        //初始化开放银行请求参数（首次运行时调用）
        //OpenBankHttpClient.initOpenBankHttpClient(appId, pfxFile, pfxPwd, cerFile, appSecret);

        // 贷款申请单H5
        applyH5();
        // 贷款申请状态查询
//        queryLoanStatus();
        // 订单支付资质核验
//        orderCheck();
        // 订单变动确认及通知
//        orderchangeinform();

    }

    @SneakyThrows
    private static void orderchangeinform() {
        String url = "https://obgateway.test.abchina.com/AraratGateWay/openabc/api/chainELoan/orderNotification/v1";
        String jsonParam = JSON.toJSONString(OrderChangeDto.mock());
        OpenBankHttpRequest request = creatRequest(url, jsonParam);

        //发送请求并接收响应报文--仅业务报文,不包含公共字段,并已经经过验签和解密:
        //设置请求超时时间（可选）
        request.setTimeout(30000);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-type", contentType);
        request.setHeader(header);
        String responseTxt = request.sendAndRecv();
        System.out.println(responseTxt);
        OrderChangeNotifyResp orderChangeNotifyResp = JSON.parseObject(responseTxt, OrderChangeNotifyResp.class);
        System.out.println(1);
    }

    @SneakyThrows
    private static void orderCheck() {
        String url = "https://obgateway.test.abchina.com/AraratGateWay/openabc/api/chainELoan/verifyElements/v1";
        String jsonParam = JSON.toJSONString(OrderCheckDto.mock());
        OpenBankHttpRequest request = creatRequest(url, jsonParam);

        //发送请求并接收响应报文--仅业务报文,不包含公共字段,并已经经过验签和解密:
        //设置请求超时时间（可选）
        request.setTimeout(30000);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-type", contentType);
        request.setHeader(header);
        String responseTxt = request.sendAndRecv();
        System.out.println(responseTxt);
        OrderCheckResp orderCheckResp = JSON.parseObject(responseTxt, OrderCheckResp.class);
        System.out.println(1);
    }

    @SneakyThrows
    private static void queryLoanStatus() {
        String url = "https://obgateway.test.abchina.com/AraratGateWay/openabc/api/chainELoan/queryApplyState/v1";
        String jsonParam = JSON.toJSONString(QueryLoanDto.mock());
        OpenBankHttpRequest request = creatRequest(url, jsonParam);

        //发送请求并接收响应报文--仅业务报文,不包含公共字段,并已经经过验签和解密:
        //设置请求超时时间（可选）
        request.setTimeout(30000);
        Map<String, Object> header = new HashMap<>();
        header.put("Content-type", contentType);
        request.setHeader(header);
        String responseTxt = request.sendAndRecv();
        System.out.println(responseTxt);
        QueryLoanStatusResp queryLoanStatusResp = JSON.parseObject(responseTxt, QueryLoanStatusResp.class);
        System.out.println(1);
    }

    @SneakyThrows
    private static void applyH5() {
        String url = "https://obgateway.test.abchina.com/AraratGateWay/openabc/h5/chainELoan/homePage/v1";
        String jsonParam = JSON.toJSONString(ApplyH5Dto.mock());

        OpenBankHttpRequest request = creatRequest(url, jsonParam);
        //用于h5页面的form表单
        String h5Url = request.getReturnRequestStringH5();
        FileUtil.writeBytes(h5Url.getBytes(), "/Users/liujf/develop/backEnd/ybm/xyy-saas-payment/h5.txt");
//        System.out.println("\"" + h5Url + "\"" );
    }


    //创建请求信息
    private static OpenBankHttpRequest creatRequest(String url, String jsonParam) throws Exception {
        OpenBankHttpRequest request = new OpenBankHttpRequest();

        //签名算法赋值,目前支持SHA256和HASHANDSHA256两种.第一种是对报文明文进行加签,一般采用这种方法,第二种是针对报文明文的哈希值进行加签;
        //报文中较长时,如含有图片信息,推荐采用"HASHANDSHA256";
        //请求或响应报文较大时,如含有图片信息,推荐采用"HASHANDSHA256",文件上传下载（Ufile）务必使用"HASHANDSHA256";
        request.setSignType(Contants.SHA256);
//        request.setSignType(Contants.HASHANDSHA256);

        //业务报文赋值-根据业务报文的格式任选一种
        int type = 1;
        if (type == 1) {
            //业务报文-普通的Json字符串
            String bizData = "{\"Code\":\"1111\"}";
            request.setBizData(jsonParam);
            request.setRequestUrl(url);
        }

        if (type == 2) {
            //业务报文-示例2--业务报文类似{"data":{"":""}}
            Map<String, Object> data = new HashMap<>();
            Map<String, Object> map = new HashMap<>();
            map.put("uscc", "110000");
            data.put("service", "queryloanstatus");
            data.put("data", map);
            request.setBizData(data);
            //10.225.188.194:9080 内网 ip 端口
            /*request.setRequestUrl("http://10.225.188.194:9080/AraratGateWay/openabc/api/sociallifepayment/gettypes/v1");
            request.setRequestUrl("https://obgateway.test.abchina.com/AraratGateWay/openabc/h5/chainELoan/homePage/v1");*/
            request.setRequestUrl("https://obgateway.test.abchina.com/AraratGateWay/openabc/api/chainELoan/queryApplyState/v1");
        }

        if (type == 3) {
            //业务报文-示例3--业务报文类似{"VALUE":""}
            Map<String, Object> map = new HashMap<>();
            map.put("VALUE", "{\"Content\":{\"Message\": {\"Version\": \"V3.0.0\", \"Format\": \"JSON\",\"Merchant\": {\"ECMerchantType\": \"EBUS\",\"MerchantID\": \"103881104410001\"}, \"TrxRequest\": {\"MerchantNo\":\"103881104410001\",\"TrxType\":\"QueryPayType\"}}},\"TransCode\":\"QueryPayType\"}");
            request.setBizData(map);
            request.setRequestUrl("http://obgateway.test.abchina.com/AraratGateWay/openabc/api/sociallifepayment/findtranstype/v1");
        }

        if (type == 4) {
            //业务报文-示例4--请求参数在header中.
            Map<String, Object> header = request.getHeader();
            header.put("Authorization", "bearer AAEAAEaZhnQajHeCPUY9y3qlmq1CgM8wSkQl-eFKMQGh96wfHpZpce21NiGzflDEi7jkpqFtzfEBHiNgqcukq0uIw4V8BJjnN1Q3dRYGH1w2kZ2IFH7c4RvvisqKgeoZWRKS7OsFopwAWP3uOlgnE_BsGdZAY99J1quIUqh-NYi06R7G8mAdJ0xge8UsfCuPqR0P0vOZmDEeMQh91zmW3dBtG5GWTJ8cmSDWBOLfbl-bVea46P0UzemjenXjFblYpCiFEcI0rZOvgsXRbKArl1AZ5093rNuStaxnnlIIQ36z2tejawc5epMbA-R5ljRZE5U4bHGbw5fHVZMTGlMfZqPpNAjUAQAAAAEAABq1bZsaLjt2o93d2lqS4JAlZern9RDz77oAaON1QnE3cNZP8EzUj0qTHc-AeJT7UjSLwR5BlNAcpaE_K_F6BN1Nu_oHb9jyui6zHXXQeOdmKQN2aNLNSJ9bmQCMYTKTKaGbpzITKiJkhTLBnBLxme_X-0KgY4yZc7GLc0E9Jq6YINhK_I-AP_NsGgDuHHjS0wqlzEVfIeyZtyKeG97Y4ol0q5FsgaJrihAco2kyGRbs9VUVL9f7fDSMpNJK_dtUm0r3f5zZHID7WkWpR6g_OSQdiYuhBXXWqLb8uMiRbpbgtnbrJuaPQHhyjE6V4xazYBbgjjbCi8h32TPb-AqizM4Nd77burWxsUs2KEQYWySN3Mh5NPl-2J9zu9j9HS00mQ2pddB_ljuAGQrlPHmsyeAGvWLrB5ZfWKWAfi2hQiNExG0-QskWgAVJSGnEFnYkbiLUh40cqoNa1zsONEJTYLapJlj9h-1UyIbV1lss3pHE8NK_0QNMkty0eBoiIjcmcRyhOzQpJ35hPbEv8TOcGlw6Ib20nwluPjeERgyg91qn_AnACH2vo8Dz3ufQLQpAB2-DknbcgJdFJnJyfZXcbW6TXaWwCygLCqe48Zqqaojq");
            request.setBizData("");
            request.setRequestUrl("http://obgateway.test.abchina.com/AraratGateWay/openabc/api/ket/userinfo/v1");
        }

        request.generateRequestString();

        return request;
    }


}
